import 'dotenv/config';
import wechatOfficialService from '../utils/WechatOfficialService';
import { prisma } from '../config/prisma';
import UserPrisma from '../models/UserPrisma';

async function backfillUnionId() {
  const users = await prisma.users.findMany({
    where: {
      wechat_official_openid: { not: null },
      union_id: null
    },
    select: {
      id: true,
      wechat_official_openid: true
    }
  });

  console.log(`待补齐 unionId 的用户数量: ${users.length}`);

  for (const item of users) {
    if (!item.wechat_official_openid) {
      continue;
    }

    try {
      const profile = await wechatOfficialService.fetchOfficialUserProfile(item.wechat_official_openid);
      const unionId = profile?.unionid;

      if (!unionId) {
        console.warn(`用户 ${item.id} 的公众号资料中缺少 unionId，跳过`);
        continue;
      }

      await UserPrisma.updateOpenPlatformBindings(item.id, { union_id: unionId });

      console.log(`用户 ${item.id} 补齐 unionId 成功`);
    } catch (error: any) {
      console.error(`用户 ${item.id} 补齐 unionId 失败:`, error?.message || error);
    }
  }
}

backfillUnionId()
  .then(() => {
    console.log('UnionId 补齐脚本执行完毕');
    process.exit(0);
  })
  .catch((error) => {
    console.error('UnionId 补齐脚本执行异常:', error);
    process.exit(1);
  });
